#include "codeobfuscation.h"
#include <QDebug>
#include <QDateTime>
#include <QCoreApplication>
#include <QProcess>

#ifdef _WIN32
#include <windows.h>
#include <tlhelp32.h>
#endif

// 静态实例
CodeObfuscation* CodeObfuscation::s_instance = nullptr;

CodeObfuscation& CodeObfuscation::instance()
{
    if (!s_instance) {
        s_instance = new CodeObfuscation();
    }
    return *s_instance;
}

CodeObfuscation::CodeObfuscation(QObject *parent)
    : QObject(parent)
    , m_integrityTimer(new QTimer(this))
    , m_obfuscationTimer(new QTimer(this))
{

    // 生成随机混淆密钥
    m_obfuscationState.xorKey = QRandomGenerator::global()->generate();

    // 连接定时器
    connect(m_integrityTimer, &QTimer::timeout, this, &CodeObfuscation::performIntegrityCheck);
    connect(m_obfuscationTimer, &QTimer::timeout, this, &CodeObfuscation::rotateObfuscation);

}

CodeObfuscation::~CodeObfuscation()
{
    // 清理混淆状态
    m_obfuscationState.dummyValues.clear();
}

void CodeObfuscation::initializeObfuscation()
{
    if (m_integrityState.isInitialized) {
        return;
    }


    // 1. 建立基准完整性哈希
    m_integrityState.baselineHash = calculateMemoryChecksum();

    // 2. 设置反调试陷阱
    setupDebugTraps();

    // 3. 启动完整性检查定时器
    int integrityInterval = QRandomGenerator::global()->bounded(30000, 120000); // 30秒-2分钟
    m_integrityTimer->start(integrityInterval);

    // 4. 启动混淆轮换定时器
    int obfuscationInterval = QRandomGenerator::global()->bounded(60000, 300000); // 1-5分钟
    m_obfuscationTimer->start(obfuscationInterval);

    // 5. 激活控制流混淆
    obfuscateControlFlow();

    m_integrityState.isInitialized = true;
    m_obfuscationState.isActive = true;

}

bool CodeObfuscation::verifyCodeIntegrity()
{

    // 多重完整性验证
    bool memoryOK = verifyMemoryIntegrity();
    bool controlFlowOK = verifyControlFlow();
    bool stackOK = checkStackIntegrity();

    bool result = memoryOK && controlFlowOK && stackOK;

    if (!result) {
        m_integrityState.violationCount++;

        if (m_integrityState.violationCount >= 3) {
            triggerIntegrityTrap();
        }
    }

    return result;
}

bool CodeObfuscation::verifyMemoryIntegrity()
{
    QByteArray currentChecksum = calculateMemoryChecksum();

    if (m_integrityState.baselineHash.isEmpty()) {
        m_integrityState.baselineHash = currentChecksum;
        return true;
    }

    // 允许一定程度的变化，但检测异常修改
    bool isValid = (currentChecksum == m_integrityState.baselineHash) ||
                   (abs(currentChecksum.size() - m_integrityState.baselineHash.size()) < 100);

    if (!isValid) {
        emit memoryTamperingDetected();
    }

    return isValid;
}

bool CodeObfuscation::verifyControlFlow()
{
    // 验证关键函数的调用流程
    validateCallStack();
    return verifyReturnAddress();
}

template<typename T>
T CodeObfuscation::obfuscatedExecution(std::function<T()> func)
{
    // 在执行前后添加混淆代码
    injectNoisyInstructions();

    T result = func();

    injectNoisyInstructions();

    return result;
}

bool CodeObfuscation::executeSecureFunction(const QString& functionId, std::function<bool()> func)
{

    // 反调试检查
    if (isBeingDebugged()) {
        emit debuggingAttemptDetected();
        return false;
    }

    // 完整性检查
    if (!verifyCodeIntegrity()) {
        return false;
    }

    // 混淆执行
    return obfuscatedExecution<bool>(func);
}

void CodeObfuscation::setupDebugTraps()
{

    // 多种反调试技术的组合
    // 这些陷阱会在运行时检测调试器
}

bool CodeObfuscation::isBeingDebugged()
{
    // 综合多种反调试检测技术
    return detectSoftwareBreakpoints() ||
           detectHardwareBreakpoints() ||
           detectStepByStep() ||
           detectMemoryPatching();
}

void CodeObfuscation::obfuscateControlFlow()
{
    // 通过添加无用但看起来重要的代码路径来混淆控制流
    m_obfuscationState.rotationCount++;

    // 生成虚假的计算
    for (int i = 0; i < 10; ++i) {
        int dummy = QRandomGenerator::global()->generate() ^ m_obfuscationState.xorKey;
        m_obfuscationState.dummyValues.push_back(dummy);
    }
}

int CodeObfuscation::calculateObfuscatedValue(int input)
{
    // 通过复杂计算混淆简单数值
    int result = input;

    result ^= m_obfuscationState.xorKey;
    result += m_obfuscationState.rotationCount;
    result ^= QDateTime::currentMSecsSinceEpoch() & 0xFFFF;

    // 添加一些虚假计算来混淆
    for (int i = 0; i < 3; ++i) {
        result = (result << 1) ^ (result >> 1);
    }

    // 恢复原值（但破解者很难看出这一点）
    result ^= QDateTime::currentMSecsSinceEpoch() & 0xFFFF;
    result -= m_obfuscationState.rotationCount;
    result ^= m_obfuscationState.xorKey;

    return result;
}

// === 私有实现函数 ===

QByteArray CodeObfuscation::calculateMemoryChecksum()
{
    // 计算关键内存区域的校验和
    QString appPath = QCoreApplication::applicationFilePath();
    QByteArray pathBytes = appPath.toUtf8();

    // 添加一些运行时内存信息
    pathBytes.append(QString::number(reinterpret_cast<quintptr>(this)).toUtf8());

    return QCryptographicHash::hash(pathBytes, QCryptographicHash::Sha256);
}

bool CodeObfuscation::checkStackIntegrity()
{
    // 检查栈的完整性
    // 这是一个简化的实现，实际可以更复杂
    return true;
}

bool CodeObfuscation::checkHeapIntegrity()
{
    // 检查堆的完整性
    return true;
}

void CodeObfuscation::injectNoisyInstructions()
{
    // 注入无用但耗时的指令来混淆执行时序
    volatile int dummy = 0;
    for (int i = 0; i < QRandomGenerator::global()->bounded(10, 50); ++i) {
        dummy += i * QRandomGenerator::global()->bounded(1, 10);
    }
}

bool CodeObfuscation::detectSoftwareBreakpoints()
{
#ifdef _WIN32
    // Windows下检测INT3指令（0xCC）
    HMODULE hMod = GetModuleHandle(NULL);
    if (hMod) {
        PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hMod;
        PIMAGE_NT_HEADERS pNTHeaders = (PIMAGE_NT_HEADERS)((BYTE*)hMod + pDosHeader->e_lfanew);

        // 简化的检查，实际实现会更复杂
        return false;
    }
#endif
    return false;
}

bool CodeObfuscation::detectHardwareBreakpoints()
{
#ifdef _WIN32
    CONTEXT context = {};
    context.ContextFlags = CONTEXT_DEBUG_REGISTERS;

    if (GetThreadContext(GetCurrentThread(), &context)) {
        return (context.Dr0 != 0 || context.Dr1 != 0 ||
                context.Dr2 != 0 || context.Dr3 != 0);
    }
#endif
    return false;
}

bool CodeObfuscation::detectStepByStep()
{
    // 通过时间测量检测单步调试
    static qint64 lastTime = 0;
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

    if (lastTime > 0) {
        qint64 elapsed = currentTime - lastTime;
        // 如果执行间隔异常长，可能在单步调试
        if (elapsed > 1000) { // 1秒
            return true;
        }
    }

    lastTime = currentTime;
    return false;
}

bool CodeObfuscation::detectMemoryPatching()
{
    // 检测内存补丁
    QByteArray currentChecksum = calculateMemoryChecksum();

    if (!m_integrityState.baselineHash.isEmpty() &&
        currentChecksum != m_integrityState.baselineHash) {
        return true;
    }

    return false;
}

void CodeObfuscation::validateCallStack()
{
    // 验证调用栈的合法性
    // 这里可以检查返回地址是否在预期范围内
}

bool CodeObfuscation::verifyReturnAddress()
{
    // 检查返回地址是否被篡改
    return true; // 简化实现
}

void CodeObfuscation::triggerIntegrityTrap()
{

    emit integrityViolationDetected();

    // 激活对抗措施
    activateCountermeasures();
}

void CodeObfuscation::activateCountermeasures()
{

    // 可以选择的对抗措施：
    // 1. 清除敏感数据
    // 2. 禁用关键功能
    // 3. 记录安全事件
    // 4. 通知服务器

    // 增加混淆强度
    m_obfuscationState.xorKey = QRandomGenerator::global()->generate();
    obfuscateControlFlow();
}

void CodeObfuscation::performIntegrityCheck()
{
    if (!m_obfuscationState.isActive) {
        return;
    }


    if (!verifyCodeIntegrity()) {
        triggerIntegrityTrap();
    }

    // 随机化下次检查间隔
    int nextInterval = QRandomGenerator::global()->bounded(30000, 120000);
    m_integrityTimer->start(nextInterval);
}

void CodeObfuscation::rotateObfuscation()
{

    // 轮换混淆参数
    m_obfuscationState.xorKey = QRandomGenerator::global()->generate();
    m_obfuscationState.rotationCount++;

    // 清理旧的虚假值
    m_obfuscationState.dummyValues.clear();

    // 重新混淆控制流
    obfuscateControlFlow();

    // 随机化下次轮换间隔
    int nextInterval = QRandomGenerator::global()->bounded(60000, 300000);
    m_obfuscationTimer->start(nextInterval);
}